package com.dvj.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dvj.common.utils.PageUtils;
import com.dvj.common.utils.Query;
import com.dvj.gulimall.product.dao.CategoryDao;
import com.dvj.gulimall.product.entity.CategoryEntity;
import com.dvj.gulimall.product.service.CategoryBrandRelationService;
import com.dvj.gulimall.product.service.CategoryService;
import com.dvj.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2.组织成父子的树形结构

        // 2.1.找到所有一级分类

        return entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildrens(menu, entities)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被被的地方引用

        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long cateLogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(cateLogId, paths);
        Collections.reverse(paths);

        return paths.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @CacheEvict(value = {"category"}, key = "'level1Categorys'")
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 每一个需要缓存的数据都指定要放定那个名字缓存。【缓存分区（按业务类型分）】
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "'level1Categorys'") // 代表当前方法的结果需要缓存，如果缓存中有，方法不用调用；如果没有，会调用方法将结果缓存起来
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    /**
     * 1.空结果缓存：解决缓存穿透
     * 2.设置过期时间（加随机值），解决缓存雪崩
     * 3.加锁，解决缓存击穿
     *
     * @return
     */
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        // 1.加入缓存逻辑,缓存中存的数据是json字符串,使用则逆转为能用的对象类型【序列化和反序列化】
        // JSON跨语言，跨平台兼容
        String catalogJson = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJson)) {
            // 2.缓存中没有，查询数据库
            return getCatalogJsonFromDBWithRedissonLock();
        }
        log.info("命中缓存...");
        return JSON.parseObject(catalogJson,
                new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
    }

    /**
     * 获取redisson分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        // 1.占分布式锁
        RLock lock = redisson.getLock("catalog-json-lock");
        lock.lock();
        log.info("获取分布式锁成功...");
        // 加锁成功...执行业务
        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            // 删除锁
            log.info("释放分布式锁成功...");
            lock.unlock();
        }
        return dataFromDB;
    }

    /**
     * 从数据库查询并封装分类数据
     * 使用redis分布锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        // 1.占分布式锁
        String lockKey = "lock";
        String uuid = UUID.randomUUID().toString();
        // 2.加锁，需要超时时间，而且需要原子性加超时时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 300, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(lock)) {
            log.info("获取分布式锁成功...");
            // 加锁成功...执行业务
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                // 删除锁，也需要原子性对比及删除
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long delLock = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                        Collections.singletonList(lockKey), uuid);
            }
            return dataFromDB;
        } else {
            log.info("获取分布式锁失败...");
            // 加锁失败...重试
            // 休眠100ms重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDBWithRedisLock();
        }


    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJson)) {
            // 如果缓存不为null直接返回
            return JSON.parseObject(catalogJson,
                    new TypeReference<Map<String, List<Catelog2Vo>>>() {
                    });
        }
        log.info("没有命中缓存，查询数据库...");
        // 将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        // 1.查出所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        // 2.封装数据
        Map<String, List<Catelog2Vo>> result = level1Categorys.stream().collect(Collectors
                .toMap(k -> k.getCatId().toString(),
                        v -> {
                            // 每一个一级分类，查到这个一级分类的耳机分类
                            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                            List<Catelog2Vo> catelog2Vos = null;
                            if (categoryEntities != null) {
                                catelog2Vos = categoryEntities.stream()
                                        .map(l2 -> {
                                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                            // 找当前二级分类的三级分类
                                            List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                                            if (level3Catelog != null) {
                                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream()
                                                        .map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                                        .collect(Collectors.toList());
                                                catelog2Vo.setCatalog3List(collect);
                                            }
                                            return catelog2Vo;
                                        })
                                        .collect(Collectors.toList());
                            }
                            return catelog2Vos != null ? catelog2Vos : new ArrayList<>();
                        }));

        // 3.查到的数据再放入缓存
        String s = JSON.toJSONString(result);
        redisTemplate.opsForValue().set("catalogJSON", s);

        return result;
    }

    /**
     * 从数据库查询并封装分类数据
     * 使用本地锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithLocalLock() {
        // TODO 改成分布式锁
        synchronized (this) {
            String catalogJson = redisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJson)) {
                // 如果缓存不为null直接返回
                return JSON.parseObject(catalogJson,
                        new TypeReference<Map<String, List<Catelog2Vo>>>() {
                        });
            }
            log.info("没有命中缓存，查询数据库...");
            // 将数据库的多次查询变为一次
            List<CategoryEntity> selectList = this.baseMapper.selectList(null);

            // 1.查出所有1级分类
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
            // 2.封装数据
            Map<String, List<Catelog2Vo>> result = level1Categorys.stream().collect(Collectors
                    .toMap(k -> k.getCatId().toString(),
                            v -> {
                                // 每一个一级分类，查到这个一级分类的耳机分类
                                List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                                List<Catelog2Vo> catelog2Vos = null;
                                if (categoryEntities != null) {
                                    catelog2Vos = categoryEntities.stream()
                                            .map(l2 -> {
                                                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                                // 找当前二级分类的三级分类
                                                List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                                                if (level3Catelog != null) {
                                                    List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream()
                                                            .map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                                            .collect(Collectors.toList());
                                                    catelog2Vo.setCatalog3List(collect);
                                                }
                                                return catelog2Vo;
                                            })
                                            .collect(Collectors.toList());
                                }
                                return catelog2Vos != null ? catelog2Vos : new ArrayList<>();
                            }));

            // 3.查到的数据再放入缓存
            String s = JSON.toJSONString(result);
            redisTemplate.opsForValue().set("catalogJSON", s);

            return result;
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
    }

    private void findParentPath(Long catelogId, List<Long> paths) {
        // 1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(getChildrens(categoryEntity, all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

}